package com.example.demo1122.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo1122.DTO.TeacherDTO;
import com.example.demo1122.domain.LoginTeacher;
import com.example.demo1122.domain.ResponseResult;
import com.example.demo1122.entity.Class;
import com.example.demo1122.entity.Course;
import com.example.demo1122.entity.Teacher;
import com.example.demo1122.entity.Teacherforclass;
import com.example.demo1122.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-12-08
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ITeacherforclassService teacherforclassService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IClassService classService;

    @Autowired
    private ICourseService courseService;
    @Autowired
    private IClassstuService classstuService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    private static final Logger logger = LoggerFactory.getLogger(TeacherController.class);
    private String fromTokenGetTeacherID(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginTeacher loginTeacher = (LoginTeacher) authentication.getPrincipal();
        String teacherID = loginTeacher.getTeacher().getTeacherID();
        return teacherID;
    }

    // 根据token返回信息
    @GetMapping("/profile")
    @ResponseBody
    public ResponseResult getProfile(){
        String teacherID = fromTokenGetTeacherID();
        Teacher teacher=teacherService.getById(teacherID);
        TeacherDTO teacherDTO=new TeacherDTO();
        teacherDTO.setTeacherID(teacher.getTeacherID());
        teacherDTO.setName(teacher.getName());
        return new ResponseResult(1,"success", teacherDTO);
    }

    //Excel导入
    @PostMapping("/upload")
    @ResponseBody
    public ResponseResult uploadExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {

            return new ResponseResult(120, "文件为空");
        }
        try {
            InputStream inputStream = file.getInputStream();

            // 使用EasyExcel读取Excel文件数据
            List<Teacher> teachers = readExcel(inputStream);

            // 在这里可以对读取到的数据进行处理，例如保存到数据库
            return teacherService.saveTeacherList(teachers);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(127, "文件上传失败");
        }
    }

    private List<Teacher> readExcel(InputStream inputStream) {
        // 使用EasyExcel读取Excel文件数据
        List<Teacher> teachers = new ArrayList<>();

        // 使用 EasyExcel.read 方法传入输入流和数据分析监听器
        EasyExcel.read(inputStream, new AnalysisEventListener<Map<Integer, String>>() {
            @Override
            public void invoke(Map<Integer, String> data, AnalysisContext context) {
                // 'data' 是一个映射，包含每一行的单元格值，键是列索引，值是单元格的值
                // 假设 'teacherID' 在第一列，'name' 在第二列
                String teacherID = data.get(0);
                String name = data.get(1);

                Teacher teacher = new Teacher();
                teacher.setTeacherID(teacherID);
                teacher.setName(name);

                teachers.add(teacher);
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // 在读取完成后执行一些操作，如果需要的话
            }
        }).sheet().doRead();

        return teachers;
    }

    // ? 新增教师，已经移到管理员的Controller


    // ? check
    //教师修改自己的信息 20240102
    @PostMapping("/update")
    @ResponseBody
    public ResponseResult update(@RequestParam(defaultValue = "") String name,
                                 @RequestParam(defaultValue = "") String password) {
        try {
            Teacher teacher = new Teacher();
            String teacherID= fromTokenGetTeacherID();
            teacher.setTeacherID(teacherID);
            teacher.setName(name);
            teacher.setPassword(password);
            Teacher teachertemp=teacherService.getById(teacherID);
            if(Objects.equals(teacher.getName(), "")){
                teacher.setName(teachertemp.getName());
            }
            if(Objects.equals(teacher.getPassword(), "")){
                teacher.setPassword(teachertemp.getPassword());
            }
            String passwordtemp = passwordEncoder.encode(teacher.getPassword());
            teacher.setPassword(passwordtemp);
            // 新增或者更新
            return teacherService.updateTeacher(teacher);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }
//查看所有教师
    @GetMapping("/findall")
    @ResponseBody
    public List<TeacherDTO> findAll() {
        List<Teacher> teachers = teacherService.list();
        List<TeacherDTO> teacherDTOs = convertToDTOList(teachers);
        return teacherDTOs;
    }

    private List<TeacherDTO> convertToDTOList(List<Teacher> teachers) {
        // 编写转换逻辑，将 Teacher 转换为 TeacherDTO
        List<TeacherDTO> teacherDTOS = new ArrayList<>();

        for (Teacher teacher : teachers) {
            TeacherDTO teacherDTO = new TeacherDTO();
            teacherDTO.setTeacherID(teacher.getTeacherID());

            teacherDTO.setName(teacher.getName());

            // 如果有其他需要转换的字段，可以继续添加

            teacherDTOS.add(teacherDTO);
        }

        return teacherDTOS;
    }

    //删除单个教师数据
    @DeleteMapping("/{teacherID}")
    @ResponseBody
    public ResponseResult delete(@PathVariable String teacherID) {

        try {
            teacherService.removeById(teacherID);
            return new ResponseResult(156, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(157, "删除失败");
        }
    }

    //批量删除教师
    @PostMapping("/del/batch")
    @ResponseBody
    public ResponseResult deleteBatch(@RequestBody List<String> teacherIDs) { // [1,2,3]
        try {
            teacherService.removeByIds(teacherIDs);
            return new ResponseResult(146, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(147, "删除失败");
        }
    }

    // 分页查询教师
    @GetMapping("/page2")
    @ResponseBody
    public ResponseResult findPage2(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String teacherID,
                                    @RequestParam(defaultValue = "") String name) {

        try {
            Page<Teacher> page = teacherService.findPage(new Page<>(pageNum, pageSize), teacherID,name);
            return new ResponseResult<>(196, "查询成功", page.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(197, "查询失败");
        }
    }
//**********************************************************************——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
    // ? check
    //教师创建课堂,创建class,classID自增；className；teacherID外键；courseID
    @PostMapping("/create/class")
    @ResponseBody
    public ResponseResult saveclass(@RequestParam String className,
                                    // @RequestParam Integer courseID
                                    @RequestParam String courseName
                                    ) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            LoginTeacher loginTeacher = (LoginTeacher) authentication.getPrincipal();
            String teacherID = loginTeacher.getTeacher().getTeacherID();
            Class class1=new Class();
            Course course=courseService.findbyname(courseName);
            class1.setClassName(className);
            class1.setTeacherID(teacherID);
            class1.setCourseID(course.getCourseID());
            // 新增
            String teachername=teacherService.getById(class1.getTeacherID()).getName();
            teacherService.saveClass(class1);
            teacherService.addTAToClass(class1.getTeacherID(), teachername, class1.getClassID());
            return new ResponseResult(502, "成功创建课堂", null);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult(500, "创建课堂失败", null);
        }
    }

    //管理员更新课堂信息
    @PostMapping("/update/class")
    @ResponseBody
    public ResponseResult updateclass(@RequestBody Class class1) {
        try {
            // 新增
            Class classtemp=classService.getById(class1.getClassID());
            if(class1.getTeacherID()==null){
                class1.setTeacherID(classtemp.getTeacherID());

            }
            if(class1.getClassName()==null){
                class1.setClassName(classtemp.getClassName());
            }
            if(class1.getCourseID()==null){
                class1.setCourseID(classtemp.getCourseID());
            }
            return teacherService.updateClass(class1);
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult(500, "更新课堂信息失败", null);
        }
    }

    // ? check
    // 教师查看自己创建的课堂信息 20240102
    @GetMapping("/findallcreate")
    @ResponseBody
    public ResponseResult findAllclass() {
        String teacherID= fromTokenGetTeacherID();
        return teacherService.findclassByTeacherId(teacherID);
    }

    // ? check
    //教师更新课堂信息 20240102
    @PostMapping("/updateclass")
    @ResponseBody
    public ResponseResult updateclassforteacher(@RequestBody Class class1) {
        try {
            String teacherID= fromTokenGetTeacherID();
            Class classtemp=classService.getById(class1.getClassID());
            if(class1.getTeacherID()==null){
                class1.setTeacherID(classtemp.getTeacherID());

            }
            if(class1.getClassName()==null){
                class1.setClassName(classtemp.getClassName());
            }
            if(class1.getCourseID()==null){
                class1.setCourseID(classtemp.getCourseID());
            }
            if(classtemp.getTeacherID().equals(teacherID)){
                // 新增
                return teacherService.updateClass(class1);
            }
            else{
                return new ResponseResult(404, "没有权限");
            }

        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult(500, "更新课堂信息失败", null);
        }
    }

    // ? check
    //教师删除自己创建的课堂 20240102
    @PostMapping("/deleteclass")
    @ResponseBody
    public ResponseResult deleteclassforteacher(@RequestParam Integer classID) {
        try {
            String teacherID= fromTokenGetTeacherID();
            Class class1=classService.getById(classID);
            if (class1==null){
                return new ResponseResult(2220, "课堂不存在", null);
            }
            if(class1.getTeacherID().equals(teacherID)){
                // 删除
                classService.removeById(class1.getClassID());
                return new ResponseResult(502, "删除成功");
            }
            else{
                return new ResponseResult(404, "没有权限");
            }

        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult(500, "删除失败", null);
        }
    }

    // 分页查询
    @GetMapping("/pageforclass")
    @ResponseBody
    public ResponseResult findPageclass(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam(defaultValue = "") Integer classID,
                                        @RequestParam(defaultValue = "") String className,
                                        @RequestParam(defaultValue = "") String teacherID,
                                        @RequestParam(defaultValue = "") Integer courseID) {

        try {
            Page<Class> page = teacherService.findPageclass(new Page<>(pageNum, pageSize), classID,className,teacherID,courseID);
            // 遍历page对象中的记录，为每个Class对象设置name和courseName
            for (Class classItem : page.getRecords()) {
                // 根据teacherID获取到教师对象从而得到教师姓名
                String name = teacherService.getById(classItem.getTeacherID()).getName();
                classItem.setName(name); // 设置教师姓名

                // // 根据courseID获取到课程对象从而得到课程姓名
                String courseName = courseService.getById(classItem.getCourseID()).getCourseName();
                classItem.setCourseName(courseName); // 设置课程名称
            }
            return new ResponseResult<>(196, "查询成功", page.getRecords());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(197, "查询失败");
        }
    }


    // 教师将助教加入课堂,先去class表查验是否是这个教师创建的课堂 20240102
    @PostMapping("/saveTAforteacher")
    @ResponseBody
    public ResponseResult saveTAforteacher(@RequestBody Teacherforclass teacherforclass
    ) {

        try {
            String teacherID= fromTokenGetTeacherID();
            if(!classService.getById(teacherforclass.getClassID()).getTeacherID().equals(teacherID)){//
                return new ResponseResult<>(404, "没有添加教师的权限", null);
            }
            // 新增或者更新
            return teacherService.addTAToClass(teacherforclass.getTeacherID(),teacherforclass.getTeacherName(),teacherforclass.getClassID());
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
            // 处理异常，将异常信息放入ResponseResult对象返回
            return new ResponseResult<>(500, "Internal Server Error", null);
        }
    }

    // 删除单个助教与课堂的连接数据 20240102 参数中的ID是会被删除的助教ID
    @DeleteMapping("/deleteTA/{classID}/{teacherID}")
    @ResponseBody
    public ResponseResult deleteta(@PathVariable Integer classID, @PathVariable String teacherID) {

        try {
            String executingteacherID= fromTokenGetTeacherID();
            String createclassteacherid = classService.getById(classID).getTeacherID();
            if(!executingteacherID.equals(createclassteacherid)){//如果从class表中查到的创建本课堂的教师ID和现在正在执行删除操作的教师ID不一致
                return new ResponseResult(404, "删除失败，没有权限");
            }
//            if(teacherID.equals(classService.getById(classID).getTeacherID())){//如果要删除的teacher是创建课堂的人，不能删除
//                return new ResponseResult(157, "删除失败，不能删除创建课堂的老师");
//            }
            boolean result = adminService.deleteTAFromClass(classID, teacherID);
            if(result) {
                return new ResponseResult(156, "删除成功");
            } else {
                return new ResponseResult(157, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(157, "删除失败，异常：" + e.getMessage());
        }
    }

    // ? check
    //根据教师ID查询课堂
    //教师查看自己加入的课堂、管理员根据教师ID查询该教师加入的课堂 20240102
    @GetMapping("/findalljoinforteacher")
    @ResponseBody
    public ResponseResult findAlljoinclass() {
        String teacherID= fromTokenGetTeacherID();
        return teacherService.findjoinclassByTeacherId(teacherID);
    }

    @GetMapping("/findallteacher/{classID}")
    @ResponseBody
    public List<TeacherDTO> findAllTeacherByClassId(@PathVariable Integer classID) {

        List<Teacher> teachers = teacherService.findTeachersByClassId(classID);
        List<TeacherDTO> teacherDTOS = convertToDTOList(teachers);
        return teacherDTOS;
    }

    @GetMapping("/findallTA/{classID}")
    @ResponseBody
    public List<TeacherDTO> findAllTAByClassId(@PathVariable Integer classID) {
        Class classtemp = classService.getById(classID);
        List<Teacher> teachers = teacherService.findTeachersByClassId(classID);
        List<TeacherDTO> teacherDTOS = new ArrayList<>();
        for (Teacher teacher : teachers) {
            if (teacher.getTeacherID().equals(classtemp.getTeacherID())){
                continue;                
            }
            TeacherDTO teacherDTO = new TeacherDTO();
            teacherDTO.setTeacherID(teacher.getTeacherID());
            teacherDTO.setName(teacher.getName());
            // 如果有其他需要转换的字段，可以继续添加
            teacherDTOS.add(teacherDTO);
        }
        return teacherDTOS;
    }

    // 教师删除单个学生与课堂的连接数据 20240102教师Controller新增
    @DeleteMapping("/deleteStudent/{classID}/{studentID}")
    @ResponseBody
    public ResponseResult delete(@PathVariable Integer classID, @PathVariable String studentID) {
        try {

            String teacherID= fromTokenGetTeacherID();
            if(!teacherforclassService.existsTeacherIdandClassID(teacherID,classID)){
                return new ResponseResult(154, "删除失败,没有权限");
            }
            boolean result = classstuService.deleteStudentFromClass(classID, studentID);
            if(result) {
                return new ResponseResult(156, "删除成功");
            } else {
                return new ResponseResult(157, "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(157, "删除失败，异常：" + e.getMessage());
        }
    }

    // 教师获取某学生在某class在某chapter下的conversation列表
    @GetMapping("/getstudentconversationlist")
    @ResponseBody
    public ResponseResult getStudentConversationList(
            @RequestParam String studentID, @RequestParam Integer classID, @RequestParam Integer chapterID ){
        return teacherforclassService.getStudentConversationList(studentID, classID, chapterID);
    }

    // 教师根据conversationID获取学生详细对话信息
    @GetMapping("/getdetailconversation")
    @ResponseBody
    public ResponseResult getDetailConversation(@RequestParam Integer conversationID ){
        return questionService.showConversation(conversationID);
    }

}
